<?php

namespace App\Http\Controllers\Api;


use App\Http\Requests\Api\AuthorizationRequest;
use App\Http\Requests\Api\StoreAuthorizationRequest;
use App\Models\User;
use Illuminate\Auth\AuthenticationException;
use Overtrue\LaravelSocialite\Socialite;


class AuthorizationsController extends Controller
{


    //第三方登录
    public function oauthStore(StoreAuthorizationRequest $request,$oauth_type)
    {
        $driver = Socialite::create($oauth_type);


        //根据哪种方式获取用户信息
        /*
         * 1. code
         * 2. token
         */
        $oauthUser = null;

        try {
            if ($code = $request->code) {
                $oauthUser = $driver->userFromCode($code);
            } else {
                $oauthUser = $driver->userFromToken($request->access_code);
            }
        } catch (\Exception $e) {
            throw new AuthenticationException("未知错误, 用户信息获取失败");
        }

        if (!$oauthUser->getId()) {
            throw new AuthenticationException('未知错误, 用户信息获取失败');
        }

        $unionid = $oauthUser->getRaw()['unionid']??null;

        $user = null;
        if (!empty($unionid)) {
            $user = User::where('weixin_unionid',$unionid)->first();
        } else {
            $user = User::where('weixin_openid',$oauthUser->getId())->first();
        }

        if (!isset($user)) {
            $user = User::create([
                "name" => $oauthUser->getNickname(),
                "avatar" => $oauthUser->getAvatar(),
                "weixin_openid" => $oauthUser->getId(),
                "weixin_unionid" => $unionid
            ]);
        }


        $token = auth('api')->login($user);
        return $this->responseWithToken($token)->setStatusCode(201);
    }

    //普通登录
    public function store(AuthorizationRequest $request)
    {
        $username = $request->username;

        $data = [];

        filter_var($username,FILTER_VALIDATE_EMAIL) ?
            $data['email'] = $username : $data['phone'] = $username;

        $data["password"] = $request->password;

        if (!$token = auth('api')->attempt($data)) {
            throw new AuthenticationException('账号或密码错误');
        }

        return $this->responseWithToken($token)->setStatusCode(201);
    }
}
